class ImageEditor {
    constructor() {
        console.log('=== ImageEditor 构造函数开始 ===');
        
        this.canvas = document.getElementById('imageCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.originalImage = null;
        this.currentImage = null;
        this.history = [];
        this.historyStep = -1;
        this.currentTool = null;
        this.cropMode = false;
        this.cropData = null;
        this.zoom = 1;
        this.isElectron = (
            typeof window !== 'undefined' && 
            window.require !== undefined && 
            typeof window.require === 'function' &&
            !window.isWebVersion && // 排除Web版本标记
            (typeof process !== 'undefined' && process.versions && process.versions.electron)
        );
        
        // 滤镜状态追踪
        this.currentFilters = {
            brightness: 0,
            contrast: 0,
            saturation: 0,
            blur: 0,
            sepia: false,
            grayscale: false
        };
        this.isDragging = false;
        this.isResizing = false;
        this.dragStart = { x: 0, y: 0 };
        this.resizeHandle = null;
        
        console.log('Canvas 元素:', this.canvas);
        console.log('Canvas 上下文:', this.ctx);
        console.log('环境检测详情:');
        console.log('  - window.require:', typeof window.require);
        console.log('  - window.isWebVersion:', window.isWebVersion);
        console.log('  - process.versions:', typeof process !== 'undefined' ? process.versions : 'undefined');
        console.log('  - 最终判断 isElectron:', this.isElectron);
        
        if (!this.canvas) {
            console.error('❗ Canvas 元素未找到！');
            return;
        }
        
        if (!this.ctx) {
            console.error('❗ Canvas 上下文获取失败！');
            return;
        }
        
        console.log('正在初始化...');
        this.init();
        console.log('=== ImageEditor 构造函数结束 ===');
    }

    init() {
        this.setupEventListeners();
        this.setupDragAndDrop();
        this.setupKeyboardShortcuts();
        this.setupCropInteraction();
        
        if (this.isElectron) {
            this.setupElectronHandlers();
        }
    }

    setupEventListeners() {
        const openBtn = document.getElementById('openBtn');
        const saveBtn = document.getElementById('saveBtn');
        
        // 调试信息
        console.log('设置事件监听器...');
        console.log('openBtn 元素:', openBtn);
        console.log('saveBtn 元素:', saveBtn);
        
        if (openBtn) {
            openBtn.addEventListener('click', () => {
                console.log('打开图片按钮被点击');
                this.openImage();
            });
        } else {
            console.error('找不到 openBtn 元素！');
        }
        
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                console.log('保存图片按钮被点击');
                this.saveImage();
            });
        } else {
            console.error('找不到 saveBtn 元素！');
        }
        
        // 其他按钮的事件监听器
        const buttons = [
            {id: 'cropBtn', handler: () => this.toggleCrop()},
            {id: 'rotateBtn', handler: () => this.rotate()},
            {id: 'flipBtn', handler: () => this.flip()},
            {id: 'resetBtn', handler: () => this.reset()},
            {id: 'undoBtn', handler: () => this.undo()},
            {id: 'redoBtn', handler: () => this.redo()},
            {id: 'zoomInBtn', handler: () => this.zoomIn()},
            {id: 'zoomOutBtn', handler: () => this.zoomOut()},
            {id: 'fitBtn', handler: () => this.fitToWindow()},
            {id: 'brightnessBtn', handler: () => this.toggleFilter('brightness')},
            {id: 'contrastBtn', handler: () => this.toggleFilter('contrast')},
            {id: 'saturationBtn', handler: () => this.toggleFilter('saturation')},
            {id: 'blurBtn', handler: () => this.toggleFilter('blur')},
            {id: 'sepiaBtn', handler: () => this.applySepia()},
            {id: 'grayscaleBtn', handler: () => this.applyGrayscale()}
        ];
        
        buttons.forEach(({id, handler}) => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener('click', handler);
                console.log(`已绑定 ${id} 事件`);
            } else {
                console.warn(`找不到元素: ${id}`);
            }
        });

        // Filter sliders
        this.setupFilterSliders();
    }

    setupFilterSliders() {
        const filters = ['brightness', 'contrast', 'saturation', 'blur'];
        
        filters.forEach(filter => {
            const slider = document.getElementById(`${filter}Slider`);
            const value = document.getElementById(`${filter}Value`);
            
            if (slider && value) {
                slider.addEventListener('input', (e) => {
                    value.textContent = e.target.value;
                    this.applyFilter(filter, parseInt(e.target.value));
                });
            }
        });
    }

    setupDragAndDrop() {
        const container = document.getElementById('canvasContainer');
        
        container.addEventListener('dragover', (e) => {
            e.preventDefault();
            container.style.backgroundColor = '#e8f4f8';
        });

        container.addEventListener('dragleave', (e) => {
            e.preventDefault();
            container.style.backgroundColor = '#ecf0f1';
        });

        container.addEventListener('drop', (e) => {
            e.preventDefault();
            container.style.backgroundColor = '#ecf0f1';
            
            const files = e.dataTransfer.files;
            if (files.length > 0 && files[0].type.startsWith('image/')) {
                this.loadImage(files[0]);
            }
        });
    }

    setupKeyboardShortcuts() {
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 'o':
                        e.preventDefault();
                        this.openImage();
                        break;
                    case 's':
                        e.preventDefault();
                        this.saveImage();
                        break;
                    case 'z':
                        e.preventDefault();
                        if (e.shiftKey) {
                            this.redo();
                        } else {
                            this.undo();
                        }
                        break;
                }
            }
            
            if (e.key === 'Escape' && this.cropMode) {
                this.toggleCrop();
            }
        });
    }

    setupElectronHandlers() {
        const { ipcRenderer } = window.require('electron');
        
        ipcRenderer.on('menu-open-file', () => {
            this.openImage();
        });
        
        ipcRenderer.on('menu-save-file', () => {
            this.saveImage();
        });
    }

    async openImage() {
        console.log('开始执行 openImage 函数...');
        console.log('isElectron:', this.isElectron);
        
        if (this.isElectron) {
            try {
                console.log('正在打开 Electron 文件对话框...');
                const { ipcRenderer } = window.require('electron');
                const result = await ipcRenderer.invoke('open-file-dialog');
                
                if (result.filePaths && result.filePaths.length > 0) {
                    const filePath = result.filePaths[0];
                    console.log('选择的文件路径:', filePath);
                    // For Electron, we'll create a File object from the path
                    // This is a simplified approach - in a real app, you'd use fs.readFileSync
                    fetch(filePath)
                        .then(response => response.blob())
                        .then(blob => {
                            const file = new File([blob], filePath.split('\\').pop());
                            this.loadImage(file);
                        })
                        .catch(error => {
                            console.error('加载图片失败:', error);
                            alert('无法加载图片文件，请检查文件是否存在或格式是否正确。');
                        });
                } else {
                    console.log('用户取消了文件选择');
                }
            } catch (error) {
                console.error('打开图片对话框失败:', error);
                alert('打开文件对话框失败，请重试。');
            }
        } else {
            console.log('正在创建 Web 端文件选择器...');
            try {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/jpeg,image/jpg,image/png,image/gif,image/bmp,image/webp';
                input.setAttribute('aria-label', '选择图片文件');
                input.style.display = 'none';
                
                console.log('文件输入元素已创建');
                
                input.onchange = (e) => {
                    console.log('文件选择发生变化');
                    try {
                        if (e.target.files && e.target.files.length > 0) {
                            const file = e.target.files[0];
                            console.log('选择的文件:', file.name, file.type, file.size);
                            // 验证文件类型
                            if (!file.type.startsWith('image/')) {
                                alert('请选择有效的图片文件！');
                                return;
                            }
                            // 验证文件大小 (最大 20MB)
                            if (file.size > 20 * 1024 * 1024) {
                                alert('图片文件过大，请选择小于20MB的文件！');
                                return;
                            }
                            console.log('开始加载图片...');
                            this.loadImage(file);
                        } else {
                            console.log('没有选择文件');
                        }
                    } catch (error) {
                        console.error('文件选择失败:', error);
                        alert('选择文件时发生错误，请重试。');
                    } finally {
                        // 清理 DOM
                        if (input.parentNode) {
                            input.parentNode.removeChild(input);
                        }
                    }
                };
                
                input.onerror = () => {
                    console.error('文件输入元素错误');
                    alert('文件选择失败，请重试。');
                    if (input.parentNode) {
                        input.parentNode.removeChild(input);
                    }
                };
                
                document.body.appendChild(input);
                console.log('文件输入元素已添加到 DOM');
                console.log('正在触发文件选择器...');
                input.click();
            } catch (error) {
                console.error('创建文件选择器失败:', error);
                alert('无法打开文件选择器，请检查浏览器设置。');
            }
        }
    }

    loadImage(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
                this.originalImage = img;
                this.currentImage = img;
                this.drawImage();
                this.saveHistory();
                this.hideDropZone();
            };
            img.src = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    drawImage() {
        if (!this.currentImage) return;

        const container = document.getElementById('canvasContainer');
        const maxWidth = container.clientWidth * 0.9;
        const maxHeight = container.clientHeight * 0.9;

        let { width, height } = this.currentImage;
        
        // Calculate scaling to fit container
        const scale = Math.min(maxWidth / width, maxHeight / height, this.zoom);
        
        this.canvas.width = width * scale;
        this.canvas.height = height * scale;
        
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.ctx.drawImage(this.currentImage, 0, 0, this.canvas.width, this.canvas.height);
    }

    hideDropZone() {
        document.getElementById('dropZone').classList.add('hidden');
    }

    saveHistory() {
        if (!this.currentImage) return;
        
        // Create a copy of current image state
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = this.canvas.width;
        tempCanvas.height = this.canvas.height;
        const tempCtx = tempCanvas.getContext('2d');
        tempCtx.drawImage(this.canvas, 0, 0);
        
        // Remove any redo history when new action is performed
        this.history = this.history.slice(0, this.historyStep + 1);
        this.history.push(tempCanvas.toDataURL());
        this.historyStep++;
    }

    undo() {
        if (this.historyStep > 0) {
            this.historyStep--;
            this.restoreFromHistory();
        }
    }

    redo() {
        if (this.historyStep < this.history.length - 1) {
            this.historyStep++;
            this.restoreFromHistory();
        }
    }

    restoreFromHistory() {
        const img = new Image();
        img.onload = () => {
            this.currentImage = img;
            this.drawImage();
        };
        img.src = this.history[this.historyStep];
    }

    toggleCrop() {
        this.cropMode = !this.cropMode;
        const cropBtn = document.getElementById('cropBtn');
        const cropOverlay = document.getElementById('cropOverlay');
        
        if (this.cropMode) {
            cropBtn.classList.add('active');
            cropOverlay.style.display = 'block';
            this.initializeCrop();
        } else {
            cropBtn.classList.remove('active');
            cropOverlay.style.display = 'none';
            this.applyCrop();
        }
    }

    initializeCrop() {
        if (!this.currentImage) {
            alert('请先打开一张图片！');
            this.toggleCrop(); // 退出裁剪模式
            return;
        }
        
        const cropOverlay = document.getElementById('cropOverlay');
        const canvas = this.canvas;
        const container = document.getElementById('canvasContainer');
        
        // 获取canvas在页面中的位置
        const canvasRect = canvas.getBoundingClientRect();
        const containerRect = container.getBoundingClientRect();
        
        // 计算裁剪框的初始大小和位置（占canvas的80%）
        const cropWidth = canvas.offsetWidth * 0.8;
        const cropHeight = canvas.offsetHeight * 0.8;
        const cropLeft = canvasRect.left + (canvas.offsetWidth - cropWidth) / 2;
        const cropTop = canvasRect.top + (canvas.offsetHeight - cropHeight) / 2;
        
        // 设置裁剪框的样式
        cropOverlay.style.position = 'fixed';
        cropOverlay.style.left = cropLeft + 'px';
        cropOverlay.style.top = cropTop + 'px';
        cropOverlay.style.width = cropWidth + 'px';
        cropOverlay.style.height = cropHeight + 'px';
        cropOverlay.style.zIndex = '1000';
        
        // 保存裁剪数据
        this.cropData = {
            x: cropLeft,
            y: cropTop,
            width: cropWidth,
            height: cropHeight,
            canvasRect: canvasRect,
            containerRect: containerRect
        };
        
        console.log('裁剪初始化:', this.cropData);
    }

    applyCrop() {
        if (!this.cropData || !this.currentImage) {
            console.log('没有裁剪数据或图片');
            return;
        }
        
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        
        // 获取当前canvas的位置信息
        const canvasRect = this.canvas.getBoundingClientRect();
        
        // 计算裁剪区域相对于canvas的比例
        const scaleX = this.currentImage.width / this.canvas.width;
        const scaleY = this.currentImage.height / this.canvas.height;
        
        // 计算裁剪区域在原图中的位置
        const cropX = Math.max(0, (this.cropData.x - canvasRect.left) * scaleX);
        const cropY = Math.max(0, (this.cropData.y - canvasRect.top) * scaleY);
        const cropWidth = Math.min(this.currentImage.width - cropX, this.cropData.width * scaleX);
        const cropHeight = Math.min(this.currentImage.height - cropY, this.cropData.height * scaleY);
        
        console.log('裁剪参数:', { cropX, cropY, cropWidth, cropHeight });
        
        // 设置临时画布大小
        tempCanvas.width = cropWidth;
        tempCanvas.height = cropHeight;
        
        // 绘制裁剪后的图片
        tempCtx.drawImage(this.currentImage, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);
        
        // 创建新图片对象
        const img = new Image();
        img.onload = () => {
            this.currentImage = img;
            this.drawImage();
            this.saveHistory();
            console.log('裁剪完成');
        };
        img.src = tempCanvas.toDataURL();
    }

    rotate() {
        if (!this.currentImage) return;
        
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        
        tempCanvas.width = this.currentImage.height;
        tempCanvas.height = this.currentImage.width;
        
        tempCtx.translate(tempCanvas.width / 2, tempCanvas.height / 2);
        tempCtx.rotate(Math.PI / 2);
        tempCtx.drawImage(this.currentImage, -this.currentImage.width / 2, -this.currentImage.height / 2);
        
        const img = new Image();
        img.onload = () => {
            this.currentImage = img;
            this.drawImage();
            this.saveHistory();
        };
        img.src = tempCanvas.toDataURL();
    }

    flip() {
        if (!this.currentImage) return;
        
        const tempCanvas = document.createElement('canvas');
        const tempCtx = tempCanvas.getContext('2d');
        
        tempCanvas.width = this.currentImage.width;
        tempCanvas.height = this.currentImage.height;
        
        tempCtx.scale(-1, 1);
        tempCtx.drawImage(this.currentImage, -this.currentImage.width, 0);
        
        const img = new Image();
        img.onload = () => {
            this.currentImage = img;
            this.drawImage();
            this.saveHistory();
        };
        img.src = tempCanvas.toDataURL();
    }

    reset() {
        if (!this.originalImage) return;
        
        this.currentImage = this.originalImage;
        this.zoom = 1;
        this.drawImage();
        this.saveHistory();
        this.resetFilters();
    }

    resetFilters() {
        const filters = ['brightness', 'contrast', 'saturation', 'blur'];
        filters.forEach(filter => {
            const slider = document.getElementById(`${filter}Slider`);
            const value = document.getElementById(`${filter}Value`);
            if (slider && value) {
                slider.value = 0;
                value.textContent = '0';
            }
            // 重置滤镜状态
            this.currentFilters[filter] = 0;
        });
        
        // 重置sepia和grayscale滤镜
        this.currentFilters.sepia = false;
        this.currentFilters.grayscale = false;
        
        // 移除按钮激活状态
        document.getElementById('sepiaBtn').classList.remove('active');
        document.getElementById('grayscaleBtn').classList.remove('active');
        
        // 清除Canvas滤镜
        this.canvas.style.filter = 'none';
        this.hideAllFilterControls();
    }

    toggleFilter(filterType) {
        const controls = document.getElementById(`${filterType}Controls`);
        const btn = document.getElementById(`${filterType}Btn`);
        
        // Hide all filter controls
        this.hideAllFilterControls();
        
        // Remove active class from all filter buttons
        document.querySelectorAll('.sidebar .btn').forEach(b => b.classList.remove('active'));
        
        if (controls.style.display === 'none' || !controls.style.display) {
            controls.classList.add('active');
            btn.classList.add('active');
        } else {
            controls.classList.remove('active');
            btn.classList.remove('active');
        }
    }

    hideAllFilterControls() {
        document.querySelectorAll('.filter-controls').forEach(controls => {
            controls.classList.remove('active');
        });
    }

    applyFilter(filterType, value) {
        if (!this.currentImage) return;
        
        // 更新滤镜状态
        this.currentFilters[filterType] = value;
        
        // 构建滤镜字符串
        const filterString = this.buildFilterString();
        
        // 应用CSS滤镜进行预览
        this.canvas.style.filter = filterString;
        
        console.log('应用滤镜:', filterType, value, '当前滤镜:', this.currentFilters);
    }
    
    buildFilterString() {
        const filters = [];
        
        if (this.currentFilters.brightness !== 0) {
            filters.push(`brightness(${100 + this.currentFilters.brightness}%)`);
        }
        if (this.currentFilters.contrast !== 0) {
            filters.push(`contrast(${100 + this.currentFilters.contrast}%)`);
        }
        if (this.currentFilters.saturation !== 0) {
            filters.push(`saturate(${100 + this.currentFilters.saturation}%)`);
        }
        if (this.currentFilters.blur !== 0) {
            filters.push(`blur(${this.currentFilters.blur}px)`);
        }
        if (this.currentFilters.sepia) {
            filters.push('sepia(100%)');
        }
        if (this.currentFilters.grayscale) {
            filters.push('grayscale(100%)');
        }
        
        return filters.join(' ');
    }

    applySepia() {
        if (!this.currentImage) return;
        
        // 切换复古滤镜状态
        this.currentFilters.sepia = !this.currentFilters.sepia;
        
        // 更新按钮状态
        const sepiaBtn = document.getElementById('sepiaBtn');
        if (this.currentFilters.sepia) {
            sepiaBtn.classList.add('active');
        } else {
            sepiaBtn.classList.remove('active');
        }
        
        // 应用滤镜
        const filterString = this.buildFilterString();
        this.canvas.style.filter = filterString;
        
        console.log('复古滤镜:', this.currentFilters.sepia ? '开启' : '关闭');
    }

    applyGrayscale() {
        if (!this.currentImage) return;
        
        // 切换黑白滤镜状态
        this.currentFilters.grayscale = !this.currentFilters.grayscale;
        
        // 更新按钮状态
        const grayscaleBtn = document.getElementById('grayscaleBtn');
        if (this.currentFilters.grayscale) {
            grayscaleBtn.classList.add('active');
        } else {
            grayscaleBtn.classList.remove('active');
        }
        
        // 应用滤镜
        const filterString = this.buildFilterString();
        this.canvas.style.filter = filterString;
        
        console.log('黑白滤镜:', this.currentFilters.grayscale ? '开启' : '关闭');
    }

    zoomIn() {
        this.zoom *= 1.2;
        this.drawImage();
    }

    zoomOut() {
        this.zoom /= 1.2;
        this.drawImage();
    }

    fitToWindow() {
        this.zoom = 1;
        this.drawImage();
    }

    async saveImage() {
        if (!this.currentImage) {
            alert('没有图片可以保存！请先打开一张图片。');
            return;
        }
        
        try {
            // 创建一个临时canvas来渲染带滤镜的图片
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');
            
            // 设置临时canvas尺寸为原图尺寸
            tempCanvas.width = this.currentImage.width;
            tempCanvas.height = this.currentImage.height;
            
            // 应用滤镜到临时canvas
            const filterString = this.buildFilterString();
            if (filterString) {
                tempCtx.filter = filterString;
                console.log('应用滤镜到保存图片:', filterString);
            }
            
            // 绘制图片到临时canvas
            tempCtx.drawImage(this.currentImage, 0, 0);
            
            // 获取渲染后的图片数据
            const dataURL = tempCanvas.toDataURL('image/png', 0.9);
            
            if (this.isElectron) {
                const { ipcRenderer } = window.require('electron');
                const result = await ipcRenderer.invoke('save-file-dialog');
                
                if (result.filePath) {
                    const fs = window.require('fs');
                    const buffer = Buffer.from(dataURL.split(',')[1], 'base64');
                    fs.writeFileSync(result.filePath, buffer);
                    alert('图片保存成功！');
                }
            } else {
                // Web端保存逻辑
                // 创建下载链接
                const link = document.createElement('a');
                const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
                link.download = `edited-image-${timestamp}.png`;
                link.href = dataURL;
                link.setAttribute('aria-label', '下载编辑后的图片');
                link.style.display = 'none';
                
                // 添加到DOM，触发下载，然后移除
                document.body.appendChild(link);
                
                // 使用 setTimeout 确保元素已添加到DOM
                setTimeout(() => {
                    try {
                        link.click();
                        console.log('下载已触发');
                        
                        // 短暂延迟后移除元素
                        setTimeout(() => {
                            if (link.parentNode) {
                                link.parentNode.removeChild(link);
                            }
                        }, 100);
                    } catch (error) {
                        console.error('下载失败:', error);
                        // 尝试备用方法
                        this.fallbackSave(dataURL);
                    }
                }, 10);
            }
        } catch (error) {
            console.error('保存图片失败:', error);
            alert('保存图片时发生错误：' + error.message);
            
            // 如果是Web端，尝试备用保存方法
            if (!this.isElectron) {
                try {
                    const dataURL = this.canvas.toDataURL('image/png', 0.9);
                    this.fallbackSave(dataURL);
                } catch (fallbackError) {
                    console.error('备用保存方法也失败:', fallbackError);
                    alert('无法保存图片，请检查浏览器设置或手动右键保存画布内容。');
                }
            }
        }
    }
    
    fallbackSave(dataURL) {
        try {
            // 备用方法：打开新窗口显示图片
            const newWindow = window.open();
            if (newWindow) {
                newWindow.document.write(`
                    <html>
                        <head><title>保存图片</title></head>
                        <body style="margin:0; display:flex; justify-content:center; align-items:center; min-height:100vh; background:#f0f0f0;">
                            <div style="text-align:center;">
                                <h3>请右键点击图片选择"图片另存为"</h3>
                                <img src="${dataURL}" style="max-width:90%; max-height:80vh; border:1px solid #ccc;" alt="编辑后的图片"/>
                            </div>
                        </body>
                    </html>
                `);
                newWindow.document.close();
            } else {
                // 如果无法打开新窗口，复制到剪贴板（如果支持）
                if (navigator.clipboard) {
                    navigator.clipboard.writeText('图片数据已准备好，但无法自动下载。请检查浏览器下载设置。');
                }
                alert('无法自动下载，请检查浏览器的弹窗和下载设置。');
            }
        } catch (error) {
            console.error('备用保存方法失败:', error);
        }
    }

    setupCropInteraction() {
        const cropOverlay = document.getElementById('cropOverlay');
        
        // 鼠标按下事件
        cropOverlay.addEventListener('mousedown', (e) => {
            if (!this.cropMode) return;
            
            e.preventDefault();
            e.stopPropagation();
            
            this.dragStart = { x: e.clientX, y: e.clientY };
            
            if (e.target.classList.contains('crop-handle')) {
                this.isResizing = true;
                this.resizeHandle = e.target.classList[1]; // nw, ne, sw, se
                console.log('开始缩放:', this.resizeHandle);
            } else {
                this.isDragging = true;
                console.log('开始拖拽');
            }
            
            // 添加全局鼠标事件监听
            document.addEventListener('mousemove', this.handleMouseMove);
            document.addEventListener('mouseup', this.handleMouseUp);
        });
        
        // 绑定事件处理函数到this
        this.handleMouseMove = this.handleMouseMove.bind(this);
        this.handleMouseUp = this.handleMouseUp.bind(this);
        
        // 双击全选功能
        cropOverlay.addEventListener('dblclick', (e) => {
            if (!this.cropMode || !this.currentImage) return;
            e.preventDefault();
            this.selectFullImage();
        });
    }
    
    handleMouseMove(e) {
        if (!this.cropMode) return;
        
        const deltaX = e.clientX - this.dragStart.x;
        const deltaY = e.clientY - this.dragStart.y;
        
        if (this.isDragging) {
            this.moveCrop(deltaX, deltaY);
        } else if (this.isResizing) {
            this.resizeCrop(deltaX, deltaY);
        }
        
        this.dragStart = { x: e.clientX, y: e.clientY };
    }
    
    handleMouseUp() {
        this.isDragging = false;
        this.isResizing = false;
        this.resizeHandle = null;
        
        // 移除全局事件监听
        document.removeEventListener('mousemove', this.handleMouseMove);
        document.removeEventListener('mouseup', this.handleMouseUp);
        
        console.log('拖拽/缩放结束');
    }
    
    selectFullImage() {
        if (!this.currentImage) return;
        
        const canvasRect = this.canvas.getBoundingClientRect();
        const cropOverlay = document.getElementById('cropOverlay');
        
        // 设置裁剪框为整个canvas大小
        cropOverlay.style.left = canvasRect.left + 'px';
        cropOverlay.style.top = canvasRect.top + 'px';
        cropOverlay.style.width = canvasRect.width + 'px';
        cropOverlay.style.height = canvasRect.height + 'px';
        
        this.cropData = {
            x: canvasRect.left,
            y: canvasRect.top,
            width: canvasRect.width,
            height: canvasRect.height,
            canvasRect: canvasRect
        };
        
        console.log('全选图片');
    }

    moveCrop(deltaX, deltaY) {
        if (!this.cropData) return;
        
        const cropOverlay = document.getElementById('cropOverlay');
        const canvasRect = this.canvas.getBoundingClientRect();
        
        // 计算新位置
        let newLeft = this.cropData.x + deltaX;
        let newTop = this.cropData.y + deltaY;
        
        // 边界检查 - 保持在canvas范围内
        newLeft = Math.max(canvasRect.left, Math.min(newLeft, canvasRect.right - this.cropData.width));
        newTop = Math.max(canvasRect.top, Math.min(newTop, canvasRect.bottom - this.cropData.height));
        
        // 更新位置
        this.cropData.x = newLeft;
        this.cropData.y = newTop;
        
        cropOverlay.style.left = newLeft + 'px';
        cropOverlay.style.top = newTop + 'px';
    }

    resizeCrop(deltaX, deltaY) {
        if (!this.cropData || !this.resizeHandle) return;
        
        const cropOverlay = document.getElementById('cropOverlay');
        const canvasRect = this.canvas.getBoundingClientRect();
        
        let newWidth = this.cropData.width;
        let newHeight = this.cropData.height;
        let newLeft = this.cropData.x;
        let newTop = this.cropData.y;
        
        // 最小尺寸限制
        const minSize = 30;
        
        switch (this.resizeHandle) {
            case 'nw': // 左上角
                newWidth = Math.max(minSize, this.cropData.width - deltaX);
                newHeight = Math.max(minSize, this.cropData.height - deltaY);
                newLeft = this.cropData.x + (this.cropData.width - newWidth);
                newTop = this.cropData.y + (this.cropData.height - newHeight);
                break;
            case 'ne': // 右上角
                newWidth = Math.max(minSize, this.cropData.width + deltaX);
                newHeight = Math.max(minSize, this.cropData.height - deltaY);
                newTop = this.cropData.y + (this.cropData.height - newHeight);
                break;
            case 'sw': // 左下角
                newWidth = Math.max(minSize, this.cropData.width - deltaX);
                newHeight = Math.max(minSize, this.cropData.height + deltaY);
                newLeft = this.cropData.x + (this.cropData.width - newWidth);
                break;
            case 'se': // 右下角
                newWidth = Math.max(minSize, this.cropData.width + deltaX);
                newHeight = Math.max(minSize, this.cropData.height + deltaY);
                break;
        }
        
        // 边界检查 - 保持在canvas范围内
        if (newLeft >= canvasRect.left && newTop >= canvasRect.top && 
            newLeft + newWidth <= canvasRect.right && newTop + newHeight <= canvasRect.bottom) {
            
            this.cropData.x = newLeft;
            this.cropData.y = newTop;
            this.cropData.width = newWidth;
            this.cropData.height = newHeight;
            
            cropOverlay.style.left = newLeft + 'px';
            cropOverlay.style.top = newTop + 'px';
            cropOverlay.style.width = newWidth + 'px';
            cropOverlay.style.height = newHeight + 'px';
        }
    }
}

// Initialize the application
document.addEventListener('DOMContentLoaded', () => {
    console.log('=== DOM内容加载完成 ===');
    console.log('window.location.href:', window.location.href);
    console.log('document.title:', document.title);
    
    // 检查关键元素是否存在
    const openBtn = document.getElementById('openBtn');
    const canvas = document.getElementById('imageCanvas');
    const container = document.getElementById('canvasContainer');
    
    console.log('openBtn 元素:', openBtn);
    console.log('canvas 元素:', canvas);
    console.log('container 元素:', container);
    
    if (!openBtn) {
        console.error('❗ 未找到 openBtn 元素！');
        // 查找所有按钮
        const allButtons = document.querySelectorAll('button');
        console.log('页面中所有按钮:', allButtons);
        allButtons.forEach((btn, index) => {
            console.log(`按钮 ${index}:`, btn.id, btn.className, btn.textContent);
        });
        return;
    }
    
    if (!canvas) {
        console.error('❗ 未找到 canvas 元素！');
        return;
    }
    
    try {
        console.log('正在创建 ImageEditor 实例...');
        const editor = new ImageEditor();
        console.log('✅ ImageEditor 实例创建成功:', editor);
        
        // 将编辑器实例暴露到全局作为调试用
        window.imageEditor = editor;
        console.log('编辑器实例已暴露为 window.imageEditor');
        
    } catch (error) {
        console.error('❗ 创建 ImageEditor 实例失败:', error);
        console.error('错误堆栈:', error.stack);
    }
});

console.log('=== renderer.js 文件已加载 ===');
console.log('当前时间:', new Date().toISOString());
console.log('document.readyState:', document.readyState);

// 测试函数 - 直接测试按钮点击
window.testButtonClick = function() {
    console.log('测试按钮点击函数被调用');
    const openBtn = document.getElementById('openBtn');
    if (openBtn) {
        console.log('找到按钮，模拟点击...');
        openBtn.click();
    } else {
        console.error('未找到 openBtn');
    }
};

// 手动测试函数
window.manualTest = function() {
    console.log('手动测试开始');
    if (window.imageEditor) {
        console.log('调用 imageEditor.openImage()');
        window.imageEditor.openImage();
    } else {
        console.error('window.imageEditor 不存在');
    }
};

// For web version (non-Electron) - 确保在ImageEditor初始化之前设置
if (typeof window !== 'undefined' && !window.require) {
    // 标记为Web版本
    window.isWebVersion = true;
    // Mock require for web version - 但不能让它被检测为真正的Electron
    // 移除模拟的require，让它保持undefined状态
}